package com.wavehi.consumer;

import com.rabbitmq.client.*;
import com.wavehi.util.RabbitMQFactoryUtils;

import java.util.HashMap;
import java.util.ListIterator;

/**
 * @Description 消费者 演示死信队列的使用
 * @Author WaveHi
 * @Date 27/12/2021 下午 9:41
 * @Version 1.0
 * @Contact HJBWaveHi@163.com
 */
public class Consumer_01 {

    //普通交换机名称
    private static final String NORMAL_EXCHANGE = "normal_exchange";
    //死信交换机名称
    private static final String DEAD_EXCHANGE = "dead_exchange";
    //普通队列名称
    private static final String NORMAL_QUEUE = "normal_queue";
    //死信队列名称
    private static final String DEAD_QUEUE = "dead_queue";

    public static void main(String[] args) throws Exception{

        //1.获取连接信道
        Channel channel = RabbitMQFactoryUtils.getChannel();
        //2.声明普通交换机
        channel.exchangeDeclare(NORMAL_EXCHANGE, BuiltinExchangeType.DIRECT);
        //3.声明死信交换机
        channel.exchangeDeclare(DEAD_EXCHANGE, BuiltinExchangeType.DIRECT);
        //4.声明死信队列
        channel.queueDeclare(DEAD_QUEUE, false, false, false, null);
        channel.queueBind(DEAD_QUEUE, DEAD_EXCHANGE, "lisi");
        //5.声明普通队列
        HashMap<String, Object> arguments = new HashMap<>();
        arguments.put("x-dead-letter-exchange", DEAD_EXCHANGE);
        arguments.put("x-dead-letter-routing-key", "lisi");
        channel.queueDeclare(NORMAL_QUEUE, false, false, false, arguments);
        //6.绑定交换机与队列
        channel.queueBind(NORMAL_QUEUE, NORMAL_EXCHANGE, "zhangsan");
        //7.接收消息
        //7.1.准备接收消息后的回调操作
        DeliverCallback deliverCallback = (consumerTag, message) -> {
            System.out.printf("Get message '%s'/n", new String(message.getBody(), "UTF-8"));
        };
        //7.2.准备消息消费中断的回调操作
        CancelCallback cancelCallback = consumerTag -> {
            System.out.println("Message consume failed!");
        };
        //7.3.接收
        channel.basicConsume(NORMAL_QUEUE, true, deliverCallback, cancelCallback);
    }
}
